<style lang='scss'>
#base-info {
  // .convert-dialog > .el-dialog {
  //   width: 1700px;
  // }

  .el-textarea.is-disabled .el-textarea__inner,
  .el-input.is-disabled .el-input__inner {
    background-color: #fff;
    border-color: #e4e7ed;
    color: #606266;
    cursor: not-allowed;
  }

  .form-table {
    .el-table__fixed-header-wrapper > table > thead > tr > th > .cell,
    .el-table__header-wrapper > table > thead > tr > th > .cell {
      padding: 10px 0;
      text-align: center;
      font-weight: bold;
    }

    .text-row {
      padding: 10px;
    }
  }

  .el-table-column--selection > .cell {
    text-align: center;
  }
  // .part {
  //   border: 1px solid #ccc;
  //   margin-bottom: 20px;
  //   background-color: #fff;
  //   .table-title {
  //     cursor: pointer;
  //     padding: 10px;
  //     display: flex;
  //     align-items: center;
  //     background-color: #f5f5f5;
  //   }
  // }
  .mt15 {
    margin-top: 15px;
  }

  .button-box {
    text-align: center;
    padding: 20px;
    background-color: #fff;
  }
}
</style>
<template>
  <div id="base-info">
    <el-tabs v-model="activeName" type="card" @tab-click="handleClick">
      <el-tab-pane label="编辑" name="edit">
        <div class="mb20">
          <el-button type="primary" @click="type = 'edit'">编辑</el-button>
          <el-button type="primary" @click="type = 'view'">查看</el-button>
        </div>
        <el-form :model="rowForm" :rules="rowFormRules" ref="rowForm" :label-position="'' | LABEL_POSITION">
          <el-table
            v-loading="regionLoading"
            element-loading-spinner="el-icon-loading"
            :data="rowForm.content.beanMapping"
            border
            class="form-table"
            :max-height="maxHeight"
            @selection-change="handleSelectionChange">
            <el-table-column v-if="type !='view'" type="selection" width="55" class="tc"></el-table-column>
            <el-table-column label="srcField" min-width="200">
              <template slot-scope="scope">
                <div v-if="type =='view'" class="text-row">{{scope.row.srcField}}</div>
                <el-form-item v-else :prop=" 'content.beanMapping.' + scope.$index + '.srcField' " :rules="rowFormRules.srcField" class="mt15">
                  <el-input
                    type="textarea"
                    :readonly="type == 'view'"
                    :autosize="{ minRows: 1, maxRows: 1}"
                    v-model="scope.row.srcField"
                    placeholder="请输入srcField"
                  ></el-input>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column label="targetField" min-width="200">
              <template slot-scope="scope">
                <div v-if="type =='view'" class="text-row">{{scope.row.targetField}}</div>
                <el-form-item
                  v-else
                  :prop=" 'content.beanMapping.' + scope.$index + '.targetField' "
                  :rules="rowFormRules.targetField"
                  class="mt15"
                >
                  <el-input
                    type="textarea"
                    :readonly="type == 'view'"
                    :autosize="{ minRows: 1, maxRows: 1}"
                    v-model="scope.row.targetField"
                    placeholder="请输入targetField"
                  ></el-input>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column label="type" min-width="200">
              <template slot-scope="scope">
                <div v-if="type =='view'" class="text-row">{{scope.row.type}}</div>
                <el-form-item v-else :prop=" 'content.beanMapping.' + scope.$index + '.type' " :rules="rowFormRules.type" class="mt15">
                  <el-input
                    type="textarea"
                    :readonly="type == 'view'"
                    :autosize="{ minRows: 1, maxRows: 1}"
                    v-model="scope.row.type"
                    placeholder="请输入type"
                  ></el-input>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column label="validate" min-width="200">
              <template slot-scope="scope">
                <div v-if="type =='view'" class="text-row">{{scope.row.validate}}</div>
                <el-form-item v-else :prop=" 'content.beanMapping.' + scope.$index + '.validate' " :rules="rowFormRules.validate" class="mt15">
                  <el-input
                    type="textarea"
                    :readonly="type == 'view'"
                    :autosize="{ minRows: 1, maxRows: 1}"
                    v-model="scope.row.validate"
                    placeholder="请输入el"
                  ></el-input>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column label="el" min-width="200">
              <template slot-scope="scope">
                <div v-if="type =='view'" class="text-row">{{scope.row.el}}</div>
                <el-form-item v-else :prop=" 'content.beanMapping.' + scope.$index + '.el' " :rules="rowFormRules.el" class="mt15">
                  <el-input
                    el="textarea"
                    :readonly="type == 'view'"
                    :autosize="{ minRows: 1, maxRows: 1}"
                    v-model="scope.row.el"
                    placeholder="请输入el"
                  ></el-input>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column label="collectionMapping" min-width="200">
              <template slot-scope="scope">
                <div v-if="type =='view'" class="text-row">{{getConfigItem(collectionMappingOpts,scope.row.collectionMapping).label}}</div>
                <el-form-item
                  v-else
                  :prop=" 'content.beanMapping.' + scope.$index + '.collectionMapping' "
                  :rules="rowFormRules.collectionMapping"
                  class="mt15"
                >
                  <el-select placeholder="请选择" v-model="scope.row.collectionMapping">
                    <el-option v-for="item in collectionMappingOpts" :key="item.value" :label="item.label" :value="item.value"></el-option>
                  </el-select>
                </el-form-item>
              </template>
            </el-table-column>

            <el-table-column label="defaultValue" min-width="200">
              <template slot-scope="scope">
                <div v-if="type =='view'" class="text-row">{{scope.row.defaultValue}}</div>
                <el-form-item
                  v-else
                  :prop=" 'content.beanMapping.' + scope.$index + '.defaultValue' "
                  :rules="rowFormRules.defaultValue"
                  class="mt15"
                >
                  <el-input
                    el="textarea"
                    :readonly="type == 'view'"
                    :autosize="{ minRows: 1, maxRows: 1}"
                    v-model="scope.row.defaultValue"
                    placeholder="请输入defaultValue"
                  ></el-input>
                </el-form-item>
              </template>
            </el-table-column>
          </el-table>

          <el-row v-if="type != 'view'">
            <el-col :span="24" class="button-box">
              <el-button type="success" @click="addItem({key:'list'})">新增Item</el-button>
              <el-button
                :disabled="selection.length == 0"
                type="warning"
                @click="delItem({key:'list.content.beanMapping',findKey:'srcField'})"
              >删除Item</el-button>
            </el-col>
          </el-row>
        </el-form>
      </el-tab-pane>
      <el-tab-pane label="JSON" name="JSON">
        <el-form id="json-form" :model="jsonForm" ref="jsonForm">
          <el-form-item prop="content" v-if="activeName == 'JSON'">
            <MonacoEditor :jsonData.sync="jsonForm.content" ref="jsonData1"></MonacoEditor>

            <!-- <el-input type="textarea"  placeholder="内容必须是标准的json格式,否则程序会报错!"   :autosize="{ minRows: 2, maxRows: 25}" v-model="jsonForm.content"></el-input> -->
          </el-form-item>
        </el-form>
      </el-tab-pane>
      <el-tab-pane label="校验请求" name="checkApi">
        <div v-if="activeName == 'checkApi'">
          <MonacoEditor :jsonData.sync="checkContent" ref="jsonData2"></MonacoEditor>
        </div>
        <el-col :span="24" class="button-box">
          <el-button type="primary" @click="checkBeanMapping">检查</el-button>
        </el-col>
      </el-tab-pane>
    </el-tabs>
    <el-row v-if="activeName != 'checkApi'">
      <el-col :span="24" class="button-box">
        <!-- <el-button type="danger" v-if=" type != 'view' " @click="onSubmitForm">删除</el-button> -->
        <el-button type="primary" @click="onSubmitForm">保存</el-button>
        <el-button @click="close">关闭</el-button>
      </el-col>
    </el-row>
  </div>
</template>
<script>
import { mapGetters, mapActions, mapState, mapMutations } from "vuex";
import SearchContainer from "src/components/common/SearchContainer";
import storage from "src/utils/storage";
import { sendReq, tableExportExcel, isJSON, copyJSONObj } from "src/utils/tools";
import { getConfigItem } from "src/utils/selectData";
import MonacoEditor from "src/components/common/MonacoEditor.vue"
import fetch from "src/utils/fetch";

let beanMappingItem = {
  srcField: '',
  type: '',
  targetField: '',
  el: '',
  validate: '',
  collectionMapping: '',
  defaultValue: '',
};

export default {
  props: ['rowForm', 'closeDialog', 'onSubmitSubForm'],

  data({rowForm}) {
    const pagePermissionsMenu = storage.get("pagePermissionsMenu")
      ? storage.get("pagePermissionsMenu")
      : {};

    const inputWarning = (msg) => {
      return [
        {
          required: true,
          message: msg,
          trigger: "blur,change"
        }
      ];
    };

    let rowFormRules = {};
    for (let key in beanMappingItem) {
      rowFormRules[key] = inputWarning(`请输入${key}`);
    }

    return {
      type: 'view',
      maxHeight: document.documentElement.clientHeight - 60 - 58 - 60 - 30 - 80,
      targetObjectOpts: ['requestConfigs', 'onsConfigs'],

      // rowForm: {
      //   list: [copyJSONObj(beanMappingItem)],
      // },
      rowFormRules: rowFormRules,
      selection: [],
      collectionMappingOpts: [
        { label: '是', value: 'Y' },
        { label: '否', value: 'N' },
      ],
      activeName:'edit',
      jsonForm:{
        ...rowForm,
        content:JSON.stringify(rowForm.content,'{}', 4)
      },
      checkContent:"",
      rowName:rowForm.name
    };
  },
  components: {
    SearchContainer,MonacoEditor
  },
  computed: {
    ...mapGetters(["pagination", "regionLoading", 'valveOpts'])
  },
  watch: {
    rowForm:function(val){
      this.jsonForm.content = JSON.stringify(this.rowForm.content,'{}', 4)
    }
    // beanMappingRow() {
    //   this.rowForm.list = this.beanMappingRow.content.beanMapping;
    // },
  },
  created() {
    
  },
  mounted() {
    //this.$emit('initEditor',this.jsonForm.content);
    //console.log('emit')
    // sendReq({
    //   url: '',
    //   params: {},
    //   cb: (data) => {
    // this.boolToStr({
    //   src: this.rowForm,
    //   to: 'str',
    //   cb: () => {
    //     this.fold.push(true);
    //   }
    // })
    //   }
    // })
    // let mockData = this.mockData;
    // this.rowForm.list = this.beanMappingRow.content.beanMapping;
    // for (let key in mockData) {
    //   if (key == 'targetObject') {
    //     this.rowForm.targetObject = mockData.targetObject;
    //   } else {
    //     mockData[key].forEach((item) => {
    //       this.rowForm.content.beanMapping.push({ srcField: '', type: key, ...item });
    //     })
    //   }
    // }

  },
  methods: {
    ...mapActions([""]),
    getConfigItem,
    close() {
      this.$emit('closeDialog');
    },
    handleSelectionChange(selection) {
      this.selection = selection;
      // console.log(selection);
    },
    addItem(obj) {
      // console.log(key);
      this.rowForm.content.beanMapping.unshift(copyJSONObj(beanMappingItem));
    },
    delItem(obj) {
      this.$confirm("确定要删除这条记录吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        this.selection.forEach((item, index) => {
          for (var i = 0, len = this.rowForm.content.beanMapping.length; i < len; i++) {
            if (this.rowForm.content.beanMapping[i][obj.findKey] == item[obj.findKey]) {
              this.rowForm.content.beanMapping.splice(i, 1);
              break;
            }
          }
        })
      })
    },
    //新增&&编辑保存
    onSubmitForm() {
      if (this.type == 'view' && this.activeName != "JSON") {
        this.type = 'edit';
        return;
      }
      let obj ;
      if(this.activeName == 'edit'){
        obj = this.rowForm;
      }else if(this.activeName == 'JSON'){
        let content = JSON.parse(this.$refs.jsonData1.getJsonData());
        obj = JSON.parse(JSON.stringify(this.jsonForm));
        obj.content = content;
      }
      
      this.$confirm("确定要提交数据吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        this.$emit('onSubmitSubForm',obj );
      })

      // let params = {
      //   type: this.type,
      // };

      // this.$refs.rowForm.validate(valid => {
      //   if (valid) {

      //     this.$confirm("确定要提交数据吗?", "提示", {
      //       confirmButtonText: "确定",
      //       cancelButtonText: "取消",
      //       type: "warning"
      //     }).then(() => {

      //       // let submitData = {};
      //       // submitData.targetObject = this.rowForm.targetObject;
      //       // this.targetObjectOpts.forEach((item) => {
      //       //   submitData[item] = [];
      //       // })
      //       // this.rowForm.content.beanMapping.forEach((item) => {
      //       //   let { srcField, creator, gmtCreated, serverUrl } = item;
      //       //   submitData[item.type].push({ srcField, creator, gmtCreated, serverUrl });
      //       // })

      //       // console.log(submitData);





      //       //   beanMapping.map((item, index) => {
      //       //     for (let key in item) {
      //       //       if (!item[key] && item[key] !== 0) {
      //       //         delete item[key];
      //       //       }
      //       //     }
      //       //     return item;
      //       //   })

      //       //   params.data = {
      //       //     key: this.type !== 'add' ? this.rowForm.key : '/plouto/convert/' + this.rowForm.key,
      //       //     content: JSON.stringify({
      //       //       targetObject: this.rowForm.targetObject,
      //       //       beanMapping: beanMapping,
      //       //     }),
      //       //     operateAction: {
      //       //       'add': '新增',
      //       //       'edit': '修改',
      //       //     }[params.type],
      //       //   }


      //       //   params.cb = () => {
      //       //     this.modifyDialogVisible = false;
      //       //     this.$refs["rowForm"] && this.$refs["rowForm"].resetFields();
      //       //     this.routerList.pageIndex = 1;
      //       //     this.getList();
      //       //     this.addHistoryRouter(params.data);
      //       //   };

      //       //   this.doZooHandlerName(params);
      //     })

      //   } else {
      //     this.$message({
      //       type: "warning",
      //       message: "请检查表单必填项!"
      //     });
      //   }
      // });
    },
    // 删除
    onDelRecord(params) {

      this.$confirm("确定要删除吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        // this.doZooHandlerName({
        //   type: 'del',
        //   data: { key: params.data.key, content: params.data.content },
        //   cb: () => {
        //     this.routerList.pageIndex = 1;
        //     this.getList();
        //   },
        // });

        // params.data.operateAction = '删除';
        // this.addHistoryRouter(params.data);


      })

    },
    handleClick() {
      if(this.activeName == 'JSON'){
        this.$nextTick (_ => {
          this.$refs.jsonData1.initEditor();
        })
      }else if(this.activeName == 'checkApi'){
        this.$nextTick (_ => {
          this.$refs.jsonData2.initEditor();
        })
      }
    },
    checkBeanMapping(){
      let content = this.$refs.jsonData2.getJsonData();
      if(!isJSON(content)){
        return 
      }
      fetch({
        url: '/config/checkConvert',
        type: "post",
        data: {
          ConvertNodeName:this.rowName,
          data:JSON.parse(content)
        },
        showRegionLoading: true,
        success: (data) => {
          if (!data) return;
          this.$message({
            type:"success",
            message:data
          })
        },
        error:(err) => {
          this.$message({
            type:"error",
            message:err
          })
        }
      })
    }
  }
};
</script>
